package com.base.animation.item

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.util.Log

/**
 * @author:zhouzechao
 * @date: 2020/12/23
 * description：
 */
private const val TAG = "BitmapDisplayItem"

class BitmapDisplayItem @JvmOverloads private constructor() : BaseDisplayItem(Paint()) {

    companion object {
        fun of(bitmap: Bitmap): BitmapDisplayItem {
            return BitmapDisplayItem().apply {
                release()
                mBitmap = bitmap
            }
        }
    }

    private var mBitmap: Bitmap? = null
        set(value) {
            field = value
            bitmapWidth = mBitmap?.width ?: 50
            bitmapHeight = mBitmap?.height ?: 50
        }

    private var bitmapWidth: Int = 50
    private var bitmapHeight: Int = 50
    private var mBitmapRect: Rect? = null
    private var mDisplayRect: RectF? = null
    private var displaySizeSet = false

    override fun draw(
        canvas: Canvas, x: Float, y: Float, alpha: Int, scaleX: Float, scaleY: Float
    ) {
        mBitmap.takeUnless { mBitmap?.isRecycled == true }?.let {
            mPaint.alpha = alpha
            mBitmap?.let {
                if (displaySizeSet) {

                    mDisplayRect?.set(x, y,
                        x + displayWidth,
                        y + displayHeight)
                    mDisplayRect?.let { rect ->
                        canvas.drawBitmap(it, mBitmapRect, rect, mPaint)
                    }
                } else {
                    Log.i(TAG, "drawX:$x --- drawY:$y  -- this:$this")
                    canvas.drawBitmap(it, x, y, mPaint)
                }
            }
        }
    }

    override fun getScalePX(scaleX: Float): Float {
        return if (displaySizeSet) {
            displayWidth * 1f / 2
        } else {
            bitmapWidth * 1f / 2
        }
    }

    override fun getScalePY(scaleY: Float): Float {
        return if (displaySizeSet) {
            displayHeight * 1f / 2
        } else {
            bitmapHeight * 1f / 2
        }
    }

    override fun getRotatePX(rotation: Float, scaleX: Float): Float {
        return if (displaySizeSet) {
            displayWidth * 1f / 2
        } else {
            bitmapWidth * 1f / 2
        }
    }

    override fun getRotatePY(rotation: Float, scaleY: Float): Float {
        return if (displaySizeSet) {
            displayHeight * 1f / 2
        } else {
            bitmapHeight * 1f / 2
        }
    }

    override fun setDisplaySize(displayWidth: Int, displayHeight: Int) {
        super.setDisplaySize(displayWidth, displayHeight)
        displaySizeSet = true
        mBitmapRect = Rect(0, 0, bitmapWidth, bitmapHeight)
        mDisplayRect = RectF()
    }

    override fun release() {
        super.release()
        displaySizeSet = false
        mBitmap?.recycle()
        mBitmap = null
    }
}